﻿using ConfigInfoWebPlatform.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;

namespace ConfigInfoWebPlatform.API.DBCommon
{
    /// <summary>
    /// 数据源
    /// </summary>
    public class DAL_DataSource
    {
        private IFreeSql freeSql;
        /// <summary>
        /// 构造
        /// </summary>
        public DAL_DataSource()
        {
            freeSql = FreesqlFactory.GetFreeSql("configplatform");
        }
        
        /// <summary>
        /// 添加数据源
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool InsertDataSource(DataSource model)
        {
            var result = freeSql.Insert<DataSource>(model).ExecuteAffrows();
            return result > 0;
        }

        /// <summary>
        /// 修改数据源信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateDataSource(DataSource model)
        {
            var result = freeSql.Update<DataSource>(model).SetSourceIgnore(model, col => col == null).ExecuteAffrows();
            return result>0;
        }

        /// <summary>
        /// 根据id删除数据源信息
        /// </summary>
        public bool DeleteDataSource(string id)
        {
            var result = freeSql.Delete<DataSource>()
                              .Where(x =>x.Id == id)
                              .ExecuteAffrows();
            return result > 0;
        }

        /// <summary>
        /// 根据条件获取数据源信息
        /// </summary>
        public List<DataSource> GetDataSourceByFilter(Expression<Func<DataSource,bool>> where)
        {
            var query = freeSql.Select<DataSource>()
                             .WhereIf(where != null, where)
                             .ToList();
            return query;
        }

        /// <summary>
        /// 通过数据源编号获取数据源信息
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public DataSource GetDataSourceByCode(string code ,string caseTypeCode)
        {
            var query = freeSql.Select<DataSource>()
                             .Where(x => x.Code == code)
                             .Where(x=>x.CaseTypeCode==caseTypeCode)
                             .ToOne();
            return query;
        }

        /// <summary>
        /// 通过id获取数据源信息
        /// </summary>
        public DataSource GetDataSourceById(string id)
        {
            var query = freeSql.Select<DataSource>()
                             .Where(x => x.Id == id)
                             .ToOne();
            return query;
        }

    }

}
